package com.relytosoft.mizar.analyze.algorithm.base.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.relytosoft.dubhe.common.core.object.ResponseResult;
import com.relytosoft.mizar.analyze.algorithm.base.service.TaskService;
import com.relytosoft.mizar.analyze.base.entity.pojo.dto.TaskRequestDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jierry
 * @version 2022/5/10.
 */
@RestController
@RequestMapping("/algo/task")
@Api(tags = "实时分析任务接口")
public class TaskBaseController {

    @Resource
    private TaskService taskService;

    @PostMapping(value = "/test")
    @ApiOperation(value = "测试")
    public ResponseResult testAuth(@RequestBody String bodys) {
        return ResponseResult.ok(taskService.test());
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "创建任务")
    public ResponseResult createTask(@RequestBody String bodys, @RequestParam(name = "statusUploadUrl", required = false) String statusUploadUrl, @RequestParam(name = "uploadUrl", required = false) String uploadUrl) {
        TaskRequestDto taskRequestDto = JSON.parseObject(bodys, TaskRequestDto.class);
        //参数验证
        String mes = this.validateTask(taskRequestDto);
        if (!StrUtil.isEmpty(mes)) {
            return ResponseResult.fail(mes);
        }
        String taskId = taskService.createTask(taskRequestDto, statusUploadUrl, uploadUrl);
        Map<String, Object> result = new HashMap<>(2);
        result.put("id", taskRequestDto.getId());
        result.put("taskId", taskId);
        return ResponseResult.ok(result);
    }

    @GetMapping(value = "/stop")
    @ApiOperation(value = "停止任务")
    public ResponseResult stopTask(@RequestParam(name = "taskId") String taskId) {
        if (StrUtil.isEmpty(taskId)) {
            return ResponseResult.fail("任务ID不能为空！");
        }
        return taskService.stopTask(taskId);
    }

    public String validateTask(TaskRequestDto taskRequestDto) {
        if (StrUtil.isEmpty(taskRequestDto.getTaskName())) {
            return "任务名称不能为空！";
        }
        if (StrUtil.isEmpty(taskRequestDto.getDeviceId())) {
            return "设备ID不能为空！";
        }
        if (StrUtil.isEmpty(taskRequestDto.getDeviceName())) {
            return "设备名称不能为空！";
        }
        if (StrUtil.isEmpty(taskRequestDto.getRtspUrl())) {
            return "设备视频流地址不能为空！";
        }
        if (taskRequestDto.getId() == null || taskRequestDto.getId() == 0) {
            return "任务ID为能为空！";
        }
        return "";
    }
}
